package com.zmn.oms.business.impl.conf.distributereason;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GlobalConsts;
import com.zmn.oms.business.interfaces.conf.distributereason.ConfOrderDistributeReasonBService;
import com.zmn.oms.common.constant.ConfRedistributeConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dro.conf.redistribute.RedistributeReasonSimpleConfDRO;
import com.zmn.oms.common.enums.ConfRedistributeAuditTypeEnum;
import com.zmn.oms.common.enums.ConfRedistributeHelpTypeEnum;
import com.zmn.oms.common.enums.ConfRedistributeTypeEnum;
import com.zmn.oms.model.bo.conf.distribute.reason.ConfOrderDistributeReasonBO;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReason;
import com.zmn.oms.model.entity.conf.distributereason.ConfOrderDistributeReasonQuery;
import com.zmn.oms.model.entity.conf.distributereason.ConfRedistributeStep;
import com.zmn.oms.model.vo.conf.distributereason.ConfOrderDistributeReasonVO;
import com.zmn.oms.services.interfaces.conf.distributereason.ConfOrderDistributeReasonService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * 类描述：派单配置
 *
 * @author liuying
 * @date 2021/11/01 13:57
 */
@Slf4j
@Service
public class ConfOrderDistributeReasonBServiceImpl implements ConfOrderDistributeReasonBService {

    @Resource
    private ConfOrderDistributeReasonService confOrderDistributeReasonService;

    @Override
    public ConfOrderDistributeReasonBO getConfOrderDistributeReasonById(Integer id) {
        ConfOrderDistributeReason redistributeReason = confOrderDistributeReasonService.findConfById(id);
        if (Objects.isNull(redistributeReason)) {
            return new ConfOrderDistributeReasonBO();
        }

        ConfOrderDistributeReasonBO redistributeReasonBO = BeanMapper.map(redistributeReason, ConfOrderDistributeReasonBO.class);

        //  工程师改派流程
        if (StringUtils.isNotBlank(redistributeReason.getEngineerRedistributeStep())){
            redistributeReasonBO.setEngineerRedistributeStep(JSON.parseObject(redistributeReason.getEngineerRedistributeStep(), ConfRedistributeStep.class));
        }

        //  系统改派流程
        if (StringUtils.isNotBlank(redistributeReason.getSystemRedistributeStep())){
            redistributeReasonBO.setSystemRedistributeStep(JSON.parseObject(redistributeReason.getSystemRedistributeStep(), ConfRedistributeStep.class));
        }

        return redistributeReasonBO;
    }

    @Override
    public List<ConfOrderDistributeReasonVO> listByQuery(ConfOrderDistributeReasonQuery query) {
        // 改派缘由 keyword 查询 【ID/缘由模糊查询】
        if (StringUtils.isNotBlank(query.getKeyWord())) {
            if (NumberUtils.isDigits(query.getKeyWord())) {
                query.setId(Integer.valueOf(query.getKeyWord()));
            } else {
                query.setReason(query.getKeyWord());
            }
        }

        List<ConfOrderDistributeReason> confList = confOrderDistributeReasonService.listByQuery(query);
        List<ConfOrderDistributeReasonVO> voList = Lists.newArrayListWithExpectedSize(confList.size());
        confList.forEach(item -> {
            ConfOrderDistributeReasonVO confOrderDistributeReasonVO = BeanMapper.map(item, ConfOrderDistributeReasonVO.class);
            confOrderDistributeReasonVO.setLiableTypeName(OrderConsts.getLiableTypeTypeName(item.getLiableType()));
            voList.add(confOrderDistributeReasonVO);
        });
        return voList;
    }

    @Override
    public List<RedistributeReasonSimpleConfDRO> listSimpleConfByQuery(ConfOrderDistributeReasonQuery query) {
        List<ConfOrderDistributeReason> confList = confOrderDistributeReasonService.listByQuery(query);
        List<RedistributeReasonSimpleConfDRO> droList = Lists.newArrayListWithExpectedSize(confList.size());
        confList.forEach(conf -> {
            RedistributeReasonSimpleConfDRO confDRO = new RedistributeReasonSimpleConfDRO();
            confDRO.setReasonId(conf.getId());
            confDRO.setReasonName(conf.getReason());

            int isNeedCheckEngineer = GlobalConsts.NO;

            if (StringUtil.isNotBlank(conf.getEngineerRedistributeStep())) {
                // 第一步为定向求助
                if (StringUtils.isNotBlank(conf.getEngineerRedistributeStep())) {
                    ConfRedistributeStep step = JSON.parseObject(conf.getEngineerRedistributeStep(), ConfRedistributeStep.class);
                    if (Objects.equals(step.getHelpType(), ConfRedistributeHelpTypeEnum.SPECIFY.getType())) {
                        isNeedCheckEngineer = GlobalConsts.YES;
                    }
                    if (Objects.equals(step.getAuditType(), ConfRedistributeAuditTypeEnum.NONE.getType())
                            && Objects.equals(step.getRedistributeType(), ConfRedistributeTypeEnum.SPECIFY.getCode()) ) {
                        isNeedCheckEngineer = GlobalConsts.YES;
                    }
                }
            }
            confDRO.setIsNeedCheckEngineer(isNeedCheckEngineer);

            droList.add(confDRO);
        });
        return droList;
    }

    @Override
    public List<ConfOrderDistributeReasonVO> listPageByQuery(ConfOrderDistributeReasonQuery query) {
        // 改派缘由 keyword 查询 【ID/缘由模糊查询】
        if (StringUtils.isNotBlank(query.getKeyWord())) {
            if (NumberUtils.isDigits(query.getKeyWord())) {
                query.setId(Integer.valueOf(query.getKeyWord()));
            } else {
                query.setReason(query.getKeyWord());
            }
        }

        query.setOrderField("sort");
        query.setDefaultOrder(1);
        List<ConfOrderDistributeReason> confList = confOrderDistributeReasonService.listPageByQuery(query);
        List<ConfOrderDistributeReasonVO> voList = Lists.newArrayListWithExpectedSize(confList.size());
        confList.forEach(item -> {
	        // 转换成VO数据
	        ConfOrderDistributeReasonVO confOrderDistributeReasonVO = BeanMapper.map(item, ConfOrderDistributeReasonVO.class);

	        // 组装字符串拼接数据
	        confOrderDistributeReasonVO.setPlat(this.getPlatTypeNameByPlatType(item.getPlat()));
	        confOrderDistributeReasonVO.setOrderTypeName(this.getOrderTypeNameByOrderType(item.getOrderType()));
	        confOrderDistributeReasonVO.setApplyTypeName(this.getApplyTypeNameByApplyType(item.getApplyType()));
	        confOrderDistributeReasonVO.setLiableTypeName(OrderConsts.getLiableTypeTypeName(item.getLiableType()));

	        voList.add(confOrderDistributeReasonVO);
        });
        return voList;
    }

    @Override
    public void modifyConfStatusById(ConfOrderDistributeReason conf) {
        Objects.requireNonNull(conf.getId(), "ID不能为空");

        ConfOrderDistributeReason updateConf = ConfOrderDistributeReason.builder()
                .id(conf.getId())
                .status(conf.getStatus())
                .updater(conf.getUpdater()).build();
        confOrderDistributeReasonService.updateSelectiveById(updateConf);
    }

    @Override
    public void modifyConfSortById(ConfOrderDistributeReason conf) {
        Objects.requireNonNull(conf.getId(), "ID不能为空");

        ConfOrderDistributeReason updateConf = ConfOrderDistributeReason.builder()
                .id(conf.getId())
                .sort(conf.getSort())
                .updater(conf.getUpdater()).build();
        confOrderDistributeReasonService.updateSelectiveById(updateConf);
    }

    /**
     * 根据平台类型，获取平台类型名称，多个名称由“逗号”隔开。
     *
     * @author liudi
     * @since: 2022/5/9 14:51
     * @param platTypes 平台类型
     * @return 拼接后的平台类型名称
     */
    private String getPlatTypeNameByPlatType(String platTypes) {
        if(StringUtils.isBlank(platTypes)){
            return "";
        }
        StringJoiner platTypeNames = new StringJoiner(",");

        List<Integer> platTypeIds = StringUtil.convertStrsToList(platTypes);
        for (Integer platTypeId : platTypeIds) {
            platTypeNames.add(GlobalConsts.getPlatName(platTypeId));
        }

        return platTypeNames.toString();
    }

    /**
     * 根据订单类型，获取订单类型名称，多个名称由“逗号”隔开。
     *
     * @author liudi
     * @since: 2022/5/9 14:51
     * @param orderTypes 订单类型
     * @return 拼接后的订单类型名称
     */
    private String getOrderTypeNameByOrderType(String orderTypes) {
        if(StringUtils.isBlank(orderTypes)){
            return "";
        }
        StringJoiner orderTypeNames = new StringJoiner(",");

        List<Integer> orderTypeIds = StringUtil.convertStrsToList(orderTypes);
        for (Integer orderTypeId : orderTypeIds) {
            orderTypeNames.add(OrderConsts.getOrderTypeName(orderTypeId));
        }

        return orderTypeNames.toString();
    }

    /**
     * 根据申请类型，获取申请类型名称，多个名称由“逗号”隔开。
     *
     * @author liudi
     * @since: 2022/5/9 14:51
     * @param applyTypes 申请类型
     * @return 拼接后的申请类型名称
     */
    private String getApplyTypeNameByApplyType(String applyTypes) {
        if(StringUtils.isBlank(applyTypes)){
            return "";
        }
        StringJoiner applyTypeNames = new StringJoiner(",");

        List<Integer> applyTypeIds = StringUtil.convertStrsToList(applyTypes);
        for (Integer applyType : applyTypeIds) {
            applyTypeNames.add(ConfRedistributeConsts.getApplyTypeName(applyType));
        }

        return applyTypeNames.toString();
    }

}
